﻿function getQueryStringParameterValue( name )
{
    name = name.replace( /[\[]/, "\\[" ).replace( /[\]]/, "\\]" );
    var regex = new RegExp( "[\\?&]" + name + "=([^&#]*)" ),
        results = regex.exec( location.search );
    return results === null ? "" : decodeURIComponent( results[1].replace( /\+/g, " " ) );
}

function createCookie( name, value, minutes )
{
    var expires;
    if ( minutes )
    {
        var date = new Date();
        date.setTime( date.getTime() + ( minutes * 60 ) );
        expires = "; expires=" + date.toGMTString();
    }
    else
    {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie( name )
{
    var nameEQ = name + "=";
    var ca = document.cookie.split( ';' );
    for ( var i = 0; i < ca.length; i++ )
    {
        var c = ca[i];
        while ( c.charAt( 0 ) == ' ' ) c = c.substring( 1, c.length );
        if ( c.indexOf( nameEQ ) == 0 ) return c.substring( nameEQ.length, c.length );
    }
    return null;
}

function eraseCookie( name )
{
    createCookie( name, "", -1 );
}

var queryStringTokenParameterValue = getQueryStringParameterValue( "token" );
if ( queryStringTokenParameterValue != '' && queryStringTokenParameterValue != null )
{
    if ( readCookie( 'io.prismic.preview' ) == null )
    {
        createCookie( 'io.prismic.preview', queryStringTokenParameterValue, 30 );
    }
}
else
{
    eraseCookie( 'io.prismic.preview' );
}